# Invite controller controls friend invitations
# In 13wins, the user may invite friends online (via FB chat) or offline (via FB messages) to earn WinPoints
# Additional WinPoints are rewarded for successful invite installs

class InvitedController < ApplicationController

  # Display offline invite info (# of WinPoints earned) and redirect to buywins 
  def index
    if i = params[:i]
    flash[:notice] = "You earned #{i*PointConfig.find_by_name("invite_sent").point} WinPoints via your invite request(s)."
    end
    redirect_to buy_wins_path
  end
  # Online Invite (via Chat) 
  def from_chat
      uid = params[:id]
        PointHistory.create(:user_id=>nil,:action=>'Invited friend from chat',:point=>PointConfig.find_by_name("invite_sent").point,:earning => true,:related_user_id=>uid)
     redirect_to bets_path
  end

  # Invoked method that user installed thirteen wins for the first time
  def after_joined
     #add extra WinPoints to online invite (via Chat) leading to installation
     phs = PointHistory.find(:all,:conditions=>["user_id is NULL and action='invite friend from chat' and created_at > ?",1.day.ago],:order=>"id desc")
     phs.each do |ph|
     if params[:fb_sig_friends].match(ph.related_user_id.to_s)
        user = User.find(ph.related_user_id)
        user.point = user.point + PointConfig.find_by_name("invite_sent").point + PointConfig.find_by_name("invite_received").point
	#user.invitation_sent_number = user.invitation_sent_number.to_i + 1
	user.invitation_accept_number = user.invitation_accept_number.to_i + 1
        user.save
	ph.user_id = params[:fb_sig_user]
	ph.save
     end
     end

     #add extra WinPoints to offline invite leading to installation
     phs_invited = PointHistory.find(:first,:conditions=>["action='Invited a friend to 13wins.' and related_user_id=?",current_user.id])
     if phs_invited
       phs_invited.user.point += 450
       PointHistory.create(:user_id=>phs_invited.user_id,:action=>'Invited friend was accept',:point=>450,:related_user_id=>nil)
       current_user.which_install = 2
       current_user.save
     end
     redirect_to "http://apps.facebook.com/thirteenwins/tutorial"
  end
end
